package com.wanmait.movies.servlet;

/**
 * Servlet implementation class UserServlet
 */


import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.apache.tomcat.jni.File;

import com.wanmait.movies.dao.CollectDao;
import com.wanmait.movies.dao.ConcernedDao;
import com.wanmait.movies.dao.DiscussDao;
import com.wanmait.movies.dao.MovieDao;
import com.wanmait.movies.dao.UserDao;
import com.wanmait.movies.vo.Collect;
import com.wanmait.movies.vo.Concerned;
import com.wanmait.movies.vo.Discuss;
import com.wanmait.movies.vo.Pager;
import com.wanmait.movies.vo.User;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
@MultipartConfig
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html ;charset=utf-8");
		//jsp�����벻ͬ��action�����й��ܲ�ͬ��servlet����
		if("veriCodeServlet".equals(request.getParameter("action"))) {//������֤��
			veriCodeServlet(request, response);
		}
		if ("checkVeriCodeServlet".equals(request.getParameter("action"))) {//��֤�û�������֤��
			checkVeriCodeServlet(request, response);
		}
		if ("checkIDServlet".equals(request.getParameter("action"))) {//��֤�˺�����
			checkIDServlet(request, response);
		}
		if ("exit".equals(request.getParameter("action"))) {//��֤�˺�����
			exit(request, response);
		}
		if ("checkUsername".equals(request.getParameter("action"))) {
			checkUsername(request,response);
		}
		if ("register".equals(request.getParameter("action"))) {
			register(request, response);
		}
		if ("rewritePersonInfo".equals(request.getParameter("action"))) {
			rewritePersonInfo(request,response);
		}
		/*if("collect".equals(request.getParameter("action"))){//���ղصĵ�Ӱ ÿ�����һҳ
			 collect(request, response);
		 }*/
		if("concerned".equals(request.getParameter("action"))) {//�ҹ�ע���� ÿ�����һҳ
			 concerned(request, response);
		 }
		if("collectdelete".equals(request.getParameter("action"))) {//ȡ���ղ�
			 collectdelete(request, response);
		 }
		if("concerneddelete".equals(request.getParameter("action"))) {//ȡ����ע
			 concerneddelete(request, response);
		 }
		if("discuss".equals(request.getParameter("action"))) {
			 discuss(request, response);
		 }
		if("discussdelete".equals(request.getParameter("action"))) {
			 discussdelete(request, response);
		 }
		if ("userPage".equals(request.getParameter("action"))) {
			userPage(request, response);
		}
		if ("userCollectAjax".equals(request.getParameter("action"))) {
			userCollectAjax(request, response);
		}
		if ("userConcernAjax".equals(request.getParameter("action"))) {
			userConcernAjax(request, response);
		}
		if ("userCommentAjax".equals(request.getParameter("action"))) {
			userCommentAjax(request, response);
		}
		if ("userRecommentAjax".equals(request.getParameter("action"))) {
			userRecommentAjax(request, response);
		}
		if ("setNewUserInfo".equals(request.getParameter("action"))) {
			setNewUserInfo(request, response);
		}
		if("shoudaoxiaoxi".equals(request.getParameter("action"))) {
			this.shoudaoxiaoxi(request, response);
		}
	}
	protected void setNewUserInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 
	}
	
	protected void userRecommentAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Pager pager = new Pager();
		User ui = (User)request.getSession().getAttribute("ui");
		DiscussDao.getObj().check(ui.getId());//����Ѳ鿴
		pager.setCurrentPager(Integer.parseInt(request.getParameter("currentPager")));
		pager.setPagerNum(DiscussDao.getObj().getpagemax(ui.getId()));
		pager.setCountinPager(pager.getPagerNum()/5+(pager.getPagerNum()%5==0?0:1));
		ArrayList<Discuss> discusses = DiscussDao.getObj().rediscuss(ui.getId(), pager.getCurrentPager());
		request.setAttribute("userrecomments", discusses);
		request.setAttribute("pagerofrecomment", pager); 
		request.getRequestDispatcher("/list.jsp").forward(request, response);
		
	}
	protected void userCommentAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Pager pager = new Pager();
		User ui = (User)request.getSession().getAttribute("ui");
		pager.setCurrentPager(Integer.parseInt(request.getParameter("currentPager")));
		pager.setPagerNum(DiscussDao.getObj().getpagemax(ui.getId()));
		pager.setCountinPager(pager.getPagerNum()/5+(pager.getPagerNum()%5==0?0:1));
		ArrayList<Discuss> discusses = DiscussDao.getObj().alldiscuss(ui.getId(), pager.getCurrentPager());
		request.setAttribute("usercomments", discusses);
		request.setAttribute("pagerofcomment", pager); 
		request.getRequestDispatcher("/list.jsp").forward(request, response);
	}
	protected void userConcernAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Pager pager = new Pager();
		User ui = (User)request.getSession().getAttribute("ui");
		pager.setCurrentPager(Integer.parseInt(request.getParameter("currentPager")));
		pager.setPagerNum(ConcernedDao.getConcerned().getPageMax(ui.getId()));
		pager.setCountinPager(pager.getPagerNum()/5+(pager.getPagerNum()%5==0?0:1));
		ArrayList<Concerned> concerneds = ConcernedDao.getConcerned().getMyConcernsed(ui.getId(), pager.getCurrentPager());
		request.setAttribute("userconcerns", concerneds);
		request.setAttribute("pagerofconcern", pager); 
		request.getRequestDispatcher("/list.jsp").forward(request, response);
	}
	protected void userCollectAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Pager pager = new Pager();
		User ui = (User)request.getSession().getAttribute("ui");
		pager.setCurrentPager(Integer.parseInt(request.getParameter("currentPager")));
		pager.setPagerNum(CollectDao.getObj().getPageMax(ui.getId()));
		pager.setCountinPager(pager.getPagerNum()/5+(pager.getPagerNum()%5==0?0:1));
		ArrayList<Collect> allcollects = CollectDao.getObj().getcollectdao(pager, ui.getId());
		request.setAttribute("usercollects", allcollects);
		request.setAttribute("pagerofcollect", pager); 
		request.getRequestDispatcher("/list.jsp").forward(request, response);
	}
	protected void userPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User ui = (User)request.getSession().getAttribute("ui");
		
		Pager pagerofcollect = new Pager();
		pagerofcollect.setCurrentPager(0);
		pagerofcollect.setPagerNum(CollectDao.getObj().getPageMax(ui.getId()));//
		pagerofcollect.setCountinPager(pagerofcollect.getPagerNum()/5+(pagerofcollect.getPagerNum()%5==0?0:1));
		ArrayList<Collect> collects = null;
		
		if (pagerofcollect.getPagerNum()!=0) {
			collects = MovieDao.getMovieDao().getUserCollects(ui.getId());
		}
		//System.out.println(collects.size()+"***************");
		request.setAttribute("pagerofcollect", pagerofcollect); 
		request.setAttribute("usercollects", collects);
		
		Pager pagerofconcern = new Pager();
		pagerofconcern.setCurrentPager(1);
		pagerofconcern.setPagerNum(ConcernedDao.getConcerned().getPageMax(ui.getId()));
		pagerofconcern.setCountinPager(pagerofconcern.getPagerNum()/5+(pagerofconcern.getPagerNum()%5==0?0:1));
		ArrayList<Concerned> concerneds = null;
		if (pagerofconcern.getPagerNum() != 0) {
			concerneds = ConcernedDao.getConcerned().getMyConcernsed(ui.getId(), pagerofconcern.getCurrentPager());
		}
		request.setAttribute("pagerofconcern", pagerofconcern);
		request.setAttribute("userconcerns", concerneds);
		
		Pager pageofcomment = new Pager();
		pageofcomment.setCurrentPager(1);
		pageofcomment.setPagerNum(DiscussDao.getObj().getpagemax(ui.getId()));
		pageofcomment.setCountinPager(pageofcomment.getPagerNum()/5+(pageofcomment.getPagerNum()%5==0?0:1));
		ArrayList<Discuss> discusses = null;
		if (pageofcomment.getPagerNum() != 0 ) {
			discusses = DiscussDao.getObj().alldiscuss(ui.getId(), pageofcomment.getCurrentPager());
		}
		request.setAttribute("pagerofcomment", pageofcomment);
		request.setAttribute("usercomments", discusses);
		
		Pager pagerofrecomment = new Pager();
		pagerofrecomment.setCurrentPager(1);
		pagerofrecomment.setPagerNum(DiscussDao.getObj().repagemax(ui.getId()));
		pagerofrecomment.setCountinPager(pagerofrecomment.getPagerNum()/5+(pagerofrecomment.getPagerNum()%5==0?0:1));
		ArrayList<Discuss> discusses2 = null;
		if (pagerofrecomment.getPagerNum() != 0) {
			discusses2 = DiscussDao.getObj().rediscuss(ui.getId(), pagerofrecomment.getCurrentPager());
		}
		request.setAttribute("pagerofrecomment", pagerofrecomment);
		request.setAttribute("userrecomments", discusses2);
		
		int ckeck = DiscussDao.getObj().getUnCkeck(ui.getId());
		request.setAttribute("ckeck", ckeck);
		request.getRequestDispatcher("/gerenkongjian.jsp").forward(request, response);
	}
	protected void checkIDServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//�õ��û�������˺�������֤���ַ���
		//�õ�session�е�ͼƬ�е���ȷ��֤��
		String username = request.getParameter("username");
		String userpass = request.getParameter("userpass");
		HttpSession session = request.getSession();
		String code = (String)session.getAttribute("code");
		String userCode = request.getParameter("codeimg");
		User ui = UserDao.getObj().getUserInfo(username, userpass);
		session.setAttribute("ui", ui);
		 
		//�ڶ��αȶ��˺��������֤�� 
		if (username.equals(ui.getUserName()) && userpass.equals(ui.getUserPassword()) && code.equalsIgnoreCase(userCode)) {
			if ("on".equals(request.getParameter("checkbox"))) {
				Cookie cookie = new Cookie("username", username);
				cookie.setPath("/movies/denglupage.jsp");
				cookie.setMaxAge(60*60*24*7);
				response.addCookie(cookie);
				Cookie cookie2 = new Cookie("userpassword", userpass);
				cookie2.setPath("/movies/denglupage.jsp");
				cookie2.setMaxAge(60*60*24*7);
				response.addCookie(cookie2);
			}
			response.sendRedirect("/movies/IndexServlet?action=begin");
			//response.sendRedirect("/movies/personinfo.jsp");
			//��ʱ�޸ģ���ת���޸ĸ�����Ϣ
		}else {
			//������ȷ���ض����ԭ��ҳ�棬���Ҵ���һ��errmesֵ
			response.sendRedirect("/movies/denglupage.jsp?errmes=1");
		}
	}
	protected void veriCodeServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int i = 0;
		String code = "";
		//��ȡ�ĸ��������ĸ��������
		while(i < 4) {
			int word = new Random().nextInt(125);
			if ((word>'0'&&word<'9')||(word>'a'&&word<'z')||(word>'A'&&word<'Z')) {
				code += (char)word;
				i++;
			}
		}
		//���壬��ȣ��߶ȣ�rgb
		BufferedImage bi = new BufferedImage(90, 30, BufferedImage.TYPE_INT_RGB);
		//����
		Graphics g = bi.getGraphics();
		//����Ӵִ�С
		g.setFont(new Font("", Font.BOLD, 25));
		//д�ڻ�����
		g.drawString(code, 10, 25);
		//IO�����                              response.getOutputStream()�ֽ������������
		ImageIO.write(bi, "jpg", response.getOutputStream());
		//session�������ɹ�������
		HttpSession session = request.getSession();
		//��code�Ž�ȥ�Ա���֤
		session.setAttribute("code", code);
		
	}
	
	protected void checkVeriCodeServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//����session����
		HttpSession session = request.getSession();
		//�õ���Ϊcode���ַ�����code��ŵ���VeriCodeServlet��������֤��ͼƬ����ĸ��������
		String code = (String)session.getAttribute("code");
		//usercode�ŵ����û��������ĸ���ߵ���
		String userCode = request.getParameter("codeText");
		//�����ִ�Сд�ıȽ�
		if (code.toLowerCase().equals(userCode.toLowerCase())) {//����equalsIgnoreCase() 
			response.getWriter().print(true);//�ظ�
		}else {
			response.getWriter().print(false);//���ظ�
		}
	
	}
	protected void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.invalidate();
		response.sendRedirect("/movies/IndexServlet?action=begin");
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	protected void checkUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String un = request.getParameter("un");
		 
		if (UserDao.getObj().checkUsername(un)) {
			response.getWriter().print(true);
		}else {
			response.getWriter().print(false);
		}
	}
	protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username = request.getParameter("name");
		String userpass = request.getParameter("mima1");
		String phonenum = request.getParameter("phonenum"); 
		UserDao.getObj().register(username,userpass,phonenum);
		 
		response.sendRedirect("/movies/denglupage.jsp");
	}
	protected void rewritePersonInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		String phonenum = request.getParameter("userphone");
		String email = request.getParameter("useremil");
		String birthday = request.getParameter("userbirthday");
		 
		Part part =request.getPart("movieImage");
		String h1 = part.getHeader("content-disposition");
		String fileName="";
		User ui = (User)request.getSession().getAttribute("ui");
		if(h1.contains("filename=\"\"")) {
			UserDao.getObj().rewriteInfo(phonenum, email, birthday, ui.getId());
		}else {
			String filepath = request.getServletContext().getRealPath("/images/");
			int i = h1.lastIndexOf(".");
			String ext = h1.substring(i,h1.length()-1);
			 fileName =UUID.randomUUID().toString()+ext;
			 part.write(filepath+"/"+fileName);
			 //part.write("E:\\images" + fileName);	
			 part.delete();
			UserDao.getObj().rewriteInfo(phonenum, email, birthday, ui.getId(),fileName);
			
		}
		
		ui = UserDao.getObj().getUser(ui.getId());
		request.getSession().setAttribute("ui", ui);
		response.sendRedirect("/movies/personinfo.jsp");
		
		
	}
	
	//点击收到消息方法
	protected void shoudaoxiaoxi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 User user =(User) request.getSession().getAttribute("ui");
		ArrayList<Integer> num = DiscussDao.getObj().shoudaoxiaoxi(user.getId());

		
		if(num!=null) {

			DiscussDao.getObj().getBit(num);
		
		}
	
	}
	protected void discuss(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   String thispage=request.getParameter("thispage");//�ҵ��ղ�
	       String user=request.getParameter("userid");
	       int pagemax= DiscussDao.getObj().getpagemax(1);
	       int userid=1;
	       if (thispage==null) {
				thispage = "1";
			}
	       if(thispage!=null){
	    	   int thispages=Integer.parseInt(thispage);
	    	   ArrayList<Discuss>alldiscuss= DiscussDao.getObj().alldiscuss(userid, thispages);
	    	   request.setAttribute("alldiscuss", alldiscuss);
	    	   request.setAttribute("ThisPage", thispages);
	    	   request.setAttribute("pagemax", pagemax);
	    	   request.getRequestDispatcher("/MyDiscuss.jsp").forward(request, response);
	       } 
	}
	protected void user(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/User.jsp").forward(request, response);
	}
	protected void discussdelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   String discussid=request.getParameter("discussid");//ɾ��������ɾ��
		 //  System.out.println(collectid);
		  DiscussDao.getObj().deleteall(discussid);
		  userPage(request,response);
		}
	protected void collectdelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	   String collectid=request.getParameter("collectid");//ɾ��������ɾ��
	 //  System.out.println(collectid);
	   
	   CollectDao.getObj().CollectDelete(collectid);
	   userPage(request,response);
	}
	protected void concerneddelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   String concernedid=request.getParameter("concernedid");//ɾ��������ɾ��
		//   System.out.println(concernedid);
		   ConcernedDao.getConcerned().ConcernedDelete(concernedid);
		   
		   userPage(request,response);
		 //  System.out.println(collectid);
		}
	protected void concerned(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
          int userId=1;//�ҵĹ�ע
          String thispage=request.getParameter("ThisPage");
          int pagemax= ConcernedDao.getConcerned().getPageMax(1);
         // System.out.println(pagemax);
          if (thispage==null) {
  			thispage = "1";
  		}
          if(thispage!=null){
	    	   int thispages=Integer.parseInt(thispage);
	    	    ArrayList<Concerned>allconcerned=ConcernedDao.getConcerned().getMyConcernsed(userId,thispages);
	    	  //  System.out.println(allconcerned.size());
	    	   request.setAttribute("allconcerned", allconcerned);
	    	   request.setAttribute("ThisPage", thispages);
	    	   request.setAttribute("pagemax", pagemax);
	    	   request.getRequestDispatcher("/MyConcerned.jsp").forward(request, response);
	       } 
	
	}
       
	/*protected void collect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   String thispage=request.getParameter("thispage");//�ҵ��ղ�
	       String user=request.getParameter("userid");
	       int pagemax= CollectDao.getObj().getPageMax(1);
	     //  System.out.println(pagemax);
	       int userid=1;
	       if (thispage==null) {
			thispage = "1";
	       }
	       if(thispage!=null){
	    	   int thispages=Integer.parseInt(thispage);
	    	   ArrayList<Collect>allcollect= CollectDao.getObj().getcollectdao(userid,thispages);
	    	 //  System.out.println(allcollect.size());
	    	   request.setAttribute("allcollect", allcollect);
	    	   request.setAttribute("ThisPage", thispages);
	    	   request.setAttribute("pagemax", pagemax);
	    	   request.getRequestDispatcher("/MyCollect.jsp").forward(request, response);
	    } 
	}
	*/


}
